﻿using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using WebMatrix.WebData;
using OpenWeb.Dal.Models;
using OpenWeb.Dal;

namespace OpenWeb.Site.Filters
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class ValidateOnActionFilter : ActionFilterAttribute
{
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            var modelState = actionExecutedContext.ActionContext.ModelState;
            if (!modelState.IsValid)
            {
                var errors = modelState
                    .Where(s => s.Value.Errors.Count > 0)
                    .Select(s => new KeyValuePair<string, string>(s.Key, s.Value.Errors.First().ErrorMessage))
                    .ToArray();

                actionExecutedContext.Result = new HttpResponseMessage<KeyValuePair<string, string>[]>(
                    errors,
                    HttpStatusCode.BadRequest
                );
            }
            base.OnActionExecuted(actionExecutedContext);
        }
}//fC




[AttributeUsage(AttributeTargets.Method | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class ValidateOnActionJsonFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var modelState = actionContext.ModelState;
        if (!modelState.IsValid)
        {
            dynamic errors = new JsonObject();
            foreach (var key in modelState.Keys)
            {
                var state = modelState[key];
                if (state.Errors.Any())
                {
                    errors[key] = state.Errors.First().ErrorMessage;
                }
            }
            actionContext.Response = new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest);
        }
    }
}//fC


  }//fN

